# -*-coding:utf-8 -*-

class Bird(object):
    def __init__(self, name='Tom'):
        self.name = name
    def printName(self):
        print 'My name is ' + self.name  
      
bird = Bird()
bird.printName()

bird2 = Bird('Jerry')
bird2.printName()

class LitterBird(Bird):
    def fly(self):
        print 'i can fly'

littleBird = LitterBird('Jack')
littleBird.printName()
littleBird.fly()

class RedBird(Bird):
    def __init__(self):
        # 重写了构造方法，要调用父类的构造，才能拥有父类的属性
#         super(RedBird, self).__init__('RRRR')
        Bird.__init__(self, 'RRRR')
        self.age = 11
    def printAge(self):
        print 'My age is', self.age

redBird = RedBird()
redBird.printAge()
redBird.printName()

# 自定义的一个List，继承自list，每次获取一次值，里面的counter都会自增1
class CounterList(list):
    def __init__(self, *args):
        super(CounterList, self).__init__(*args)
        self.count = 0
    def __getitem__(self, index):
        self.count += 1
        return super(CounterList, self).__getitem__(index)
    def __delitem__(self, index):
        self.count -= 1
        return super(CounterList, self).__delitem__(index)

cl = CounterList([1, 2, 4, 5, 6, 7])
print 'cl.count=' , cl.count
print 'cl[0]=' , cl[0]
print 'cl.count=' , cl.count
print 'cl[-1]=' , cl[-1]
print 'cl.count=' , cl.count
del cl[-1]
print 'cl.count=' , cl.count
print cl


'''property函数'''
class Rectangle(object):
    def __init__(self):
        self.width=0
        self.height=0
    #返回宽高的元组
    def getSize(self):
        return self.width,self.height
    def setSize(self,size):
        self.width,self.height=size
        
    size=property(getSize,setSize)
     
r=Rectangle()
r.width=50
r.height=100
print r.size
r.size=200,300
print r.size

'''类方法和静态方法'''
class Test(object):
    
    @staticmethod
    def staticMethod():
        print 'I am a static method'
        
    @classmethod
    def classMethod(cls):#注意这个cls，必须要，可以自己命名
        print 'I am a class method'
        
Test.staticMethod()
Test.classMethod()

'''生成器'''
gen=(x+1 for x in range(10))

print gen.next()
print gen.next()
print gen.next()
#前面如果调用了next，这里会从后面开始遍历
for i in gen:
    print i

'''生成器是一个包含yield的函数，遇到yield或return会生成一个值'''
#递归生成器
def flatten(nested):
    try:
        for sublist in nested:
            for element in flatten(sublist):
                yield element
    except TypeError:
        yield nested
print list(flatten([[1,2,3,[4,[99,88]]],[6,7,8],9,10]))